package com.piggy.oss.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.map.MapUtil;
import com.piggy.oss.cloud.OSSFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class DownloadUtils {
    public static void downloadBatchFile(List<String> fileNames, String zipName, HttpServletResponse response) {

        Map<String, InputStream> map = MapUtil.newHashMap();
        fileNames.forEach(i -> map.put(i, IoUtil.toStream(OSSFactory.build().downloadFile(i))));

        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipName, "UTF-8"));
//			zipName = new String(zipName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
//			response.setHeader("Content-Disposition", "attachment;filename=" + zipName);
            ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());

            map.forEach((fileName, is) -> DownloadUtils.addToZip(is, zipOut, fileName));
            zipOut.flush();
            zipOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /*添加压缩文件*/
    private static void addToZip(InputStream is, ZipOutputStream zipOut, String fileName) {
        try {
            ZipEntry entry = new ZipEntry(fileName);
            zipOut.putNextEntry(entry);
            int len;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) > 0) {
                zipOut.write(buffer, 0, len);
            }
            zipOut.closeEntry();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
